package com.example.lcpractice.lc;

import com.example.lcpractice.datastructure.LinkedList;
import com.example.lcpractice.datastructure.ListNode;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 148. 排序链表
 * 中等
 * 给你链表的头结点 head ，请将其按 升序 排列并返回 排序后的链表 。
 * 输入：head = [4,2,1,3]
 * 输出：[1,2,3,4]
 * 示例 3：
 * <p>
 * 输入：head = []
 * 输出：[]
 * <p>
 * <p>
 * 提示：
 * <p>
 * 链表中节点的数目在范围 [0, 5 * 104] 内
 * -105 <= Node.val <= 105
 */
public class Lc148 {
    public static void main(String[] args) {
        ListNode linkedList = LinkedList.getLinkedList();
        linkedList.setVal(999);
        sortList(linkedList);
    }

    public static ListNode sortList(ListNode head) {
        if (head == null) {
            return null;
        }
        List<ListNode> nodeList = new ArrayList<>();
        while (head != null) {
            nodeList.add(new ListNode(head.val));
            head = head.next;
        }
        List<ListNode> collect = nodeList.stream().sorted(Comparator.comparingInt(n -> n.val)).collect(Collectors.toList());
        ListNode header = new ListNode();
        ListNode p = header;
        for (ListNode node : collect) {
            p.next = node;
            p = p.next;
        }

        return header.next;
    }


}
